package com.javalong.affairs.adapter;

import java.util.ArrayList;
import java.util.List;

import android.R.bool;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;

import com.javalong.affairs.R;
import com.javalong.affairs.model.User;

public class ReceiverAdapter extends BaseAdapter {
	private List<User> selectedUsers;
	private Type type;

	public ReceiverAdapter(Context context, List<User> userList, Type type) {
		super(context, userList);
		selectedUsers = new ArrayList<User>();
		this.type = type;
	}

	public List<User> getSelectedUsers() {
		return selectedUsers;
	}

	@Override
	public void notifyDataSetChanged() {
		super.notifyDataSetChanged();
		selectedUsers.clear();
	}
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		final User user = (User) getItem(position);
		ViewHolder holder;
		if (convertView != null) {
			holder = (ViewHolder) convertView.getTag();
		} else {
			holder = new ViewHolder();
			convertView = mInflater.inflate(R.layout.item_receiver, null);
			holder.tv_user = (TextView) convertView.findViewById(R.id.tv_user);
			holder.cb_user = (CheckBox) convertView.findViewById(R.id.cb_user);
			convertView.setTag(holder);
		}

		if (user != null) {
			holder.tv_user.setText(user.userName);

			switch (type) {
			case DELEGATE:
				holder.cb_user.setVisibility(View.GONE);
				break;
			case RECEIVER:
				holder.cb_user
						.setOnCheckedChangeListener(new OnCheckedChangeListener() {
							@Override
							public void onCheckedChanged(
									CompoundButton buttonView, boolean isChecked) {
								if (isChecked) {
									if (!selectedUsers.contains(user)) {
										selectedUsers.add(user);
									}
								} else {
									if (selectedUsers.contains(user)) {
										selectedUsers.remove(user);
									}
								}
							}
						});
				break;
			}
			if (selectedUsers.contains(user)) {
				holder.cb_user.setChecked(true);
			} else {
				holder.cb_user.setChecked(false);
			}
		}
		return convertView;
	}

	class ViewHolder {
		CheckBox cb_user;
		TextView tv_user;
	}

	public enum Type {
		DELEGATE, RECEIVER
	}
}
